package com.king.hpeproject.controller.base;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * BaseController 类描述
 *
 * @author xxx
 * @since 2025/8/20
 */
public class BaseController {
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 从请求参数、表单或JSON Body中提取 字段值
     */
    protected List<String> extractFromRequest(HttpServletRequest requestWrapper, List<String> paramNames) throws IOException {
        if (StringUtils.equalsAnyIgnoreCase(requestWrapper.getMethod(), HttpMethod.GET.name(),
                HttpMethod.DELETE.name())) {
            for (String fieldName : paramNames) {
                String fieldValue = requestWrapper.getParameter(fieldName);
                if (fieldValue != null) {
                    return Arrays.asList(fieldValue.split(","));
                }
            }
        } else if (StringUtils.equalsAnyIgnoreCase(requestWrapper.getMethod(), HttpMethod.POST.name(),
                HttpMethod.PUT.name())) {  // 从JSON Body获取
            List<String> paramValueList = new ArrayList<>();
            try (InputStream inputStream = requestWrapper.getInputStream()) {
                JsonNode rootNode = objectMapper.readTree(inputStream);
                for (String fieldName : paramNames) {
                    JsonNode fieldNode = rootNode.path(fieldName);
                    if (fieldNode.isArray()) {
                        fieldNode.forEach(node -> paramValueList.add(node.asText()));
                    } else if (fieldNode.isTextual()) {
                        paramValueList.add(fieldNode.asText());
                    }
                    if (!paramValueList.isEmpty()) {
                        return paramValueList;
                    }
                }
            }
        }

        return Collections.emptyList();
    }
}
